package com.nervenets.shopping.controller.user.params;

import com.nervenets.general.Global;
import com.nervenets.general.exception.LogicException;
import com.nervenets.general.utils.StringUtils;
import com.nervenets.general.web.params.FormParams;
import com.nervenets.shopping.enumeration.Gender;
import com.nervenets.shopping.hibernate.domain.user.Manager;
import com.nervenets.shopping.service.ManagerService;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class ManagerFormParams extends FormParams<Manager, ManagerService> {
    @ApiModelProperty(value = "账号", required = true)
    @NotBlank
    @Size(min = 5, max = 20)
    private String mobile;
    @ApiModelProperty(value = "密码，为空则不修改")
    private String password;
    @ApiModelProperty(value = "昵称", required = true)
    @NotBlank
    @Size(min = 2, max = 20)
    private String name;
    @ApiModelProperty(value = "头像")
    private String avatar;
    @ApiModelProperty(value = "性别")
    private Gender gender = Gender.female;
    @ApiModelProperty(value = "是否启用")
    private boolean enable = true;

    @Override
    public Manager validateAndBuild(ManagerService service, HttpServletRequest request, HttpServletResponse response) {
        Manager manager = new Manager();
        if (getFormId() > 0) {
            manager = service.findOne(getFormId(), "您要编辑的数据不存在，请刷新后再试。");
        }
        BeanUtils.copyProperties(this, manager, Global.defaultIgnoreProperties());
        if (StringUtils.isBlank(password)) {
            if (manager.isNew()) throw new LogicException("请输入6-20位密码");
        } else {
            if (password.length() < 6 || password.length() > 20) {
                throw new LogicException("请输入6-20位密码");
            }
            manager.setPassword(password);
        }

        if (service.hasUniqueKey(manager.getId(), "mobile", getMobile())) {
            throw new LogicException(String.format("已存在【%s】账号", getMobile()));
        }

        return manager;
    }
}
